package com.booter.consumer.controller;


import javax.servlet.AsyncContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ConcurrentHashMap;


/**
 * spring boot 启用servlet 有两种方式
 * 1 @ServletComponentScan 开启扫描注解
 * 2 通过ServletRegistrationBean 注册
 */
@WebServlet(name = "asyServlet", urlPatterns = "user/push", asyncSupported = true)
public class AsycServletController extends HttpServlet {
    private static final long serialVersionUID = 6003423066510322153L;
    private static final Map<String, GetClient> clients = new ConcurrentHashMap<String, GetClient>();

    static {
        //启动一个线程，扫描，关闭所有超时的连接
        new Timer().schedule(new TimerTask() {
            @Override
            public void run() {
                long current = System.currentTimeMillis();
                for (Map.Entry<String, GetClient> entry : clients.entrySet()) {
                    GetClient client = entry.getValue();
                    if (client == null) {
                        return;
                    }
                    if (current - client.time > 20 * 1000) {
                        client.complete();
                        clients.remove(entry.getKey());
                    }
                }
            }
        }, 10, 5000);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        //拉数据
        if ("get".equals(action)) {
            final AsyncContext asyncContext = req.startAsync();
            asyncContext.setTimeout(0L);//代表连接不过期
            String uid = req.getParameter("uid");
            clients.put(uid, new GetClient(asyncContext, uid));
            //设置数据
        } else if ("set".equals(action)) {
            String msg = req.getParameter("msg");
            this.sendMsg(msg);
            resp.getWriter().print("set success");
        }
    }

    /**
     * 消息发送给所有客户端
     *
     * @param msg
     */
    private void sendMsg(String msg) {
        Iterator<String> users = clients.keySet().iterator();
        while (users.hasNext()) {
            GetClient cl = clients.get(users.next());
            if (cl != null) {
                cl.response(msg);
            }
        }
    }
}

/**
 * 客户端连接对象
 */
class GetClient {

    public AsyncContext asyncContext;
    public String uid;
    public long time;

    public GetClient(AsyncContext asyncContext, String uid) {
        this.asyncContext = asyncContext;
        this.uid = uid;
        this.time = System.currentTimeMillis();
    }

    //关闭连接
    public void complete() {
        this.response("connect end");
        this.asyncContext.complete();
    }

    public static DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    //响应
    public void response(String message) {
        Map<String, Object> content = new HashMap<String, Object>();
        content.put("messages", message);
        try {
            HttpServletResponse response = (HttpServletResponse) this.asyncContext.getResponse();
            PrintWriter writer = response.getWriter();
            response.setHeader("Content-type", "text/html;charset=UTF-8");
            writer.println(format.format(new Date()) + ",receive:" + content + "<br/>");
            writer.flush();
        } catch (Exception se) {
        }
    }


}
